const crypto = require("crypto");
const fs = require("fs-extra");
const path = require("path");
const Decrypter = require('aes-decrypter').Decrypter;
const M3U8 = require("m3u8-parser");
// const AES = require("aes");
const lib = require("./lib");
// debugger
const encryptedVideoKey = "4a64aa235435b75bf1f20fd1e0f37097"
const IV = "0xf3bb6b0f97b2ed0357ec32a450b1e64b";


function chuliEncryptedVideoKey(encryptedVideoKey) {
  var _encryptedVideoKey = encryptedVideoKey || "56d2703684b07b3e87ed290676c1cb84"
  let _key = lib.utf8_toBytes('72Fhskjglp8qjpqx');
  let _aesEcb = new lib.ModeOfOperationECB(_key);
  var _bbb = [];
  for (var i = 0; i < _encryptedVideoKey.length; i += 2) {
    _bbb.push(parseInt(_encryptedVideoKey[i] + _encryptedVideoKey[i + 1], 16));
  }
  var _decryptedBytes = _aesEcb.decrypt(_bbb);
  var _decryptedText = lib.convertUtf8.fromBytes(_decryptedBytes)
  let key = lib.str2ab(_decryptedText);
  let view = new DataView(key);
  let segmentKeyBytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  // debugger
  return segmentKeyBytes;
}

fs.readFile(path.join(__dirname, "./mda-ikai4z4my5ycufmc.m3u8"), async (err, m3u8Data) => {
  var parser = new M3U8.Parser();
  parser.push(m3u8Data.toString());
  let encryptedVideoKey = "56d2703684b07b3e87ed290676c1cb84"
  let decedVideoKey = chuliEncryptedVideoKey(encryptedVideoKey);
  let iv = parser.manifest.segments[0].key.iv;
  let tsdata = await fs.readFile(path.join(__dirname,"./enc0.ts"));
  new Decrypter(tsdata,decedVideoKey,iv,async (err,decryptedBytes)=>{
    debugger
    await fs.writeFile(path.join(__dirname,"dec0.ts"),decryptedBytes);
    debugger
  })
  debugger
})


chuliEncryptedVideoKey();

